<template>
  <div class="quality-inspection-container">
    <!-- 搜索区域 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item>
          <el-input v-model="searchForm.inspector" placeholder="检测人员工号" style="width: 150px;" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="searchForm.startInspectionTime"
            type="datetime"
            placeholder="开始检测时间"
            style="width: 200px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-date-picker
            v-model="searchForm.endInspectionTime"
            type="datetime"
            placeholder="结束检测时间"
            style="width: 200px;">
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
          <el-button type="success" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <el-table 
      :data="tableData" 
      border 
      style="width: 100%" 
      v-loading="loading"
      :height="400"
      :row-style="{height:'60px'}"
      :cell-style="{padding:'0px'}"
      :header-row-style="{height:'50px'}"
      :header-cell-style="{padding:'0px'}">
      <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
      <el-table-column prop="batchId" label="批次ID" width="120" align="center"></el-table-column>
      <el-table-column prop="inspector" label="检测人员编号" width="120" align="center"></el-table-column>
      <el-table-column prop="inspectionTime" label="检测时间" width="180" align="center">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.inspectionTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="inspectionItems" label="检测项目" width="150" align="center"></el-table-column>
      <el-table-column prop="results" label="检测结果" width="150" align="center"></el-table-column>
      <el-table-column prop="status" label="状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 0 ? 'danger' : 'success'">
            {{ scope.row.status === 0 ? '不合格' : '合格' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="reportUrl" label="检测报告" width="120" align="center">
        <template slot-scope="scope">
          <el-button 
            v-if="scope.row.reportUrl"
            type="text"
            @click="handleViewReport(scope.row.reportUrl)">
            查看报告
          </el-button>
          <span v-else>无报告</span>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" width="180" align="center">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.createTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" min-width="180" align="center">
        <template slot-scope="scope">
          {{ formatDateTime(scope.row.updateTime) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" align="center" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            circle
            class="operation-button"
            @click="handleEdit(scope.row)"
            title="编辑">
          </el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            circle
            class="operation-button"
            @click="handleDelete(scope.row)"
            title="删除">
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="page"
        :page-sizes="[5, 10, 20, 50, 100]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" :close-on-click-modal="false">
      <el-form :model="form" :rules="rules" ref="form" label-width="120px">
        <el-form-item label="批次ID" prop="batchId">
          <el-select 
            v-model="form.batchId" 
            placeholder="请选择批次号" 
            style="width: 100%" 
            @focus="getBatchList">
            <el-option
              v-for="id in batchOptions"
              :key="id"
              :label="id"
              :value="id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="检测人员编号" prop="inspector">
          <el-input v-model="form.inspector" placeholder="请输入检测人员工号" style="width: 100%"></el-input>
        </el-form-item>
        <el-form-item label="检测时间" prop="inspectionTime">
          <el-date-picker
            v-model="form.inspectionTime"
            type="datetime"
            placeholder="选择检测时间"
            style="width: 100%">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="检测项目" prop="inspectionItems">
          <el-input type="textarea" v-model="form.inspectionItems" placeholder="请输入检测项目(JSON格式)" :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="检测结果" prop="results">
          <el-input type="textarea" v-model="form.results" placeholder="请输入检测结果(JSON格式)" :rows="3"></el-input>
        </el-form-item>
        <el-form-item label="检测报告" prop="reportUrl">
          <el-upload
            class="upload-demo"
            action="/api/file/uploadFile"
            :headers="uploadHeaders"
            :on-success="handleReportSuccess"
            :before-upload="beforeReportUpload">
            <el-button size="small" type="primary">点击上传</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="不合格" :value="0"></el-option>
            <el-option label="合格" :value="1"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import http from '@/http/http'
import moment from 'moment'

export default {
  name: 'QualityInspection',
  data() {
    return {
      // 搜索表单
      searchForm: {
        inspector: '',
        startInspectionTime: null,
        endInspectionTime: null
      },
      // 表格数据
      tableData: [],
      loading: false,
      // 分页
      page: 1,
      pageSize: 5,
      total: 0,
      // 对话框
      dialogVisible: false,
      dialogTitle: '新增质量检测',
      // 批次选项
      batchOptions: [],
      // 表单
      form: {
        id: null,
        batchId: '',
        inspector: '',
        inspectionTime: null,
        inspectionItems: '',
        results: '',
        reportUrl: '',
        status: 0
      },
      // 表单验证规则
      rules: {
        batchId: [
          { required: true, message: '请输入批次ID', trigger: 'blur' }
        ],
        inspector: [
          { required: true, message: '请输入检测人员工号', trigger: 'blur' }
        ],
        inspectionTime: [
          { required: true, message: '请选择检测时间', trigger: 'change' }
        ],
        inspectionItems: [
          { required: true, message: '请输入检测项目', trigger: 'blur' }
        ],
        results: [
          { required: true, message: '请输入检测结果', trigger: 'blur' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ]
      },
      uploadHeaders: {
        'Authorization': localStorage.getItem('token') || ''
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    formatDateTime(time) {
      return time ? moment(time).format('YY-MM-DD HH:mm:ss') : '--'
    },
    // 获取数据
    async fetchData() {
      this.loading = true
      try {
        const params = {
          page: this.page,
          pageSize: this.pageSize
        }
        const res = await http.qualityInspection.getList(params)
        if (res.data.code === 200) {
          this.tableData = res.data.data
          this.total = res.data.total
        }
      } catch (error) {
        console.error('获取数据失败:', error)
        this.$message.error('获取数据失败')
      } finally {
        this.loading = false
      }
    },

    // 获取批次列表
    async getBatchList() {
      try {
        const res = await http.processingBatch.getBatchNo()
        if (res.data.code === 200) {
          this.batchOptions = res.data.data
        }
      } catch (error) {
        console.error('获取批次列表失败:', error)
        this.$message.error('获取批次列表失败')
      }
    },

    // 搜索
    async handleSearch() {
      this.page = 1
      this.loading = true
      try {
        const params = {
          page: this.page,
          pageSize: this.pageSize,
          inspector: this.searchForm.inspector || null,
          startInspectionTime: this.searchForm.startInspectionTime,
          endInspectionTime: this.searchForm.endInspectionTime
        }
        const res = await http.qualityInspection.getByCondition(params)
        if (res.data.code === 200) {
          this.tableData = res.data.data
          this.total = res.data.total
        }
      } catch (error) {
        console.error('搜索失败:', error)
        this.$message.error('搜索失败')
      } finally {
        this.loading = false
      }
    },

    // 重置搜索
    resetSearch() {
      this.searchForm = {
        inspector: '',
        startInspectionTime: null,
        endInspectionTime: null
      }
      this.page = 1
      this.fetchData()
    },

    // 新增
    handleAdd() {
      this.dialogTitle = '新增质量检测'
      this.form = {
        id: null,
        batchId: '',
        inspector: '',
        inspectionTime: null,
        inspectionItems: '',
        results: '',
        reportUrl: '',
        status: 0
      }
      this.dialogVisible = true
    },

    // 编辑
    handleEdit(row) {
      this.dialogTitle = '编辑质量检测'
      this.form = { ...row }
      this.dialogVisible = true
    },

    // 删除
    handleDelete(row) {
      this.$confirm('确认删除该质量检测记录?', '提示', {
        type: 'warning'
      }).then(async () => {
        try {
          const res = await http.qualityInspection.deleteInspection(row.id)
          if (res.data.code === 200) {
            this.$message.success('删除成功')
            this.fetchData()
          }
        } catch (error) {
          this.$message.error('删除失败')
        }
      }).catch(() => {})
    },

    // 提交表单
    submitForm() {
      this.$refs.form.validate(async (valid) => {
        if (valid) {
          try {
            const res = await http.qualityInspection.save(this.form)
            if (res.data.code === 200) {
              this.$message.success(this.form.id ? '更新成功' : '添加成功')
              this.dialogVisible = false
              this.fetchData()
            } else {
              this.$message.error(res.data.msg || '操作失败')
            }
          } catch (error) {
            this.$message.error(this.form.id ? '更新失败' : '添加失败')
          }
        }
      })
    },

    // 分页相关方法
    handleSizeChange(val) {
      this.pageSize = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.page = val
      this.fetchData()
    },

    // 查看报告
    handleViewReport(url) {
      window.open(url, '_blank')
    },

    // 报告上传前的验证
    beforeReportUpload(file) {
      const isPDF = file.type === 'application/pdf'
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isPDF) {
        this.$message.error('上传文件只能是 PDF 格式!')
        return false
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!')
        return false
      }
      return true
    },

    // 报告上传成功的回调
    handleReportSuccess(res) {
      if (res.code === 200) {
        this.form.reportUrl = res.data
        this.$message.success('报告上传成功')
      } else {
        this.$message.error(res.msg || '报告上传失败')
      }
    }
  }
}
</script>

<style scoped>
.quality-inspection-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 100px);
}

.search-bar {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  align-items: center;
}

/* 重置输入框样式 */
.search-form .el-input__inner {
  background-color: #fff;
  border: 1px solid #dcdfe6;
  color: #606266;
  text-align: left;
}

.search-form .el-input__inner:hover {
  border-color: #c0c4cc;
}

.search-form .el-input__inner:focus {
  border-color: #409EFF;
}

.el-button + .el-button {
  margin-left: 12px;
}

.el-table {
  margin-top: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.pagination-container {
  text-align: right;
  margin-top: 20px;
  padding: 20px;
  background-color: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

/* 操作按钮样式 */
.operation-button.el-button.is-circle {
  width: 36px;
  height: 36px;
  padding: 9px;
  transition: all 0.3s ease;
  margin: 0 8px;
}

.operation-button.el-button.is-circle [class^="el-icon-"] {
  font-size: 16px;
  line-height: 1;
  vertical-align: -1px;
}

.operation-button.el-button.is-circle:hover {
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

/* 编辑按钮特定样式 */
.operation-button.el-button--primary.is-circle {
  background: linear-gradient(135deg, #409EFF, #3a8ee6);
}

/* 删除按钮特定样式 */
.operation-button.el-button--danger.is-circle {
  background: linear-gradient(135deg, #f56c6c, #e74c3c);
}

/* 表单输入框左对齐 */
.el-form-item .el-input__inner,
.el-form-item .el-input-number__decrease,
.el-form-item .el-input-number__increase {
  text-align: left;
}

.el-form-item .el-input-number .el-input__inner {
  text-align: left;
  padding-left: 8px;
}

/* 设置表格行高 */
.el-table /deep/ .el-table__row {
  height: 67px !important;
}

/* 设置表头行高 */
.el-table /deep/ .el-table__header-row {
  height: 50px !important;
}

/* 设置单元格内边距和行高 */
.el-table /deep/ .cell {
  padding: 0 !important;
  line-height: 69px;
}

/* 设置表头单元格行高 */
.el-table /deep/ .el-table__header .cell {
  line-height: 50px;
}
</style>
